<?php
namespace app\admin\model;

use think\Model;

class Policy extends Model
{
	public function savePolicy(array $policyInfo)
	{
	    $result = false;
		$policy = new Policy;
		if (isset($policyInfo['id']) && $policyInfo['id'] != null ){
		    $id = $policyInfo['id'];
		    unset($policyInfo['id']);
		    $policyInfo['created'] = time();
		    $result = $policy->save($policyInfo,['id'=>$id]);
		}else {
			$policy->policy = $policyInfo['policy'];
			$policy->created = time();
			$policy->createdwho = $policyInfo['createdwho'];
			$policy->attachments = $policyInfo['attachments'];
			$policy->content = $policyInfo['content'];
			$policy->to_where = $policyInfo['to_where'];
			$policy->save();
			$result = $policy->id;
		}

		return $result;
	}

	private function ifUniqueUsedFile($policyId,$filePath)
    {
        $result = array('if_has' => false,'info' => array());
        $all_attachments = db('policy')->where('id','<>',$policyId)->select(['id','policy','attachments']);
        foreach ($all_attachments as $ak => $av){
            $has = [
                'id' => $av['id'],
                'policy' => $av['policy'],
            ];
            $attachments = json_decode($av['attachments']);
            foreach ($attachments as $aak => $aav){
                if ($filePath == $aav['path']){
                    $result['if_has'] = true;
                    array_push($result['info'],$has);
                    break;
                }
            }
        }
       return $result;
    }


    public function del_attachments($policyId, $filePath)
    {
        $result = array('result' => false,'message' => '','info' => array());
        $attachments_org = db('policy')->where('id',$policyId)->value('attachments');
        $attachments = array();
        $attachments_org = json_decode($attachments_org,true);
        foreach ($attachments_org as $ak => $av){
            if ($av['path'] == $filePath){
                $result['result'] = true;
                continue;
            }
            array_push($attachments,$av);
        }
        $attachments = json_encode($attachments,JSON_UNESCAPED_UNICODE);
        $update_attachments = db('policy')->where('id',$policyId)->update(['attachments' => $attachments]);
        if ($update_attachments == false){
            $result['result'] = false;
            $result['message'] = '更新文件附件失败！';
            return $result;
        }
        $if_unique_used = $this->ifUniqueUsedFile($policyId,$filePath);
        if ($if_unique_used['if_has']){
            $result['message'] = '删除成功！还有以下文件共用此附件：';
            $result['info'] = $if_unique_used['info'];
        }else{
            $path_prefix = ROOT_PATH.'Uploads'.DS.'policy'.DS;
            $file_name = iconv('utf-8','gb2312',$path_prefix.$filePath);
            unlink($file_name);
            $result['message'] = '该附件已删除';
        }
        return $result;
    }
    
    public function diffValue(array $newArray,array $oldArray)
    {
    	$result = array();
    	$newArray = is_array($newArray) ? $newArray:array();
    	$oldArray = is_array($oldArray) ? $oldArray:array();
    	foreach ($newArray as $nk => &$nv){
    		$nv = json_encode($nv);
    	}
    	foreach ($oldArray as $ok => &$ov){
    		$ov = json_encode($ov);
    	}
    	$result = array_diff($newArray, $oldArray);
    	foreach ($result as $rk => &$rv){
    		$rv = json_decode($rv,true);
    	}
    	return $result;
    }

    public function reorganizeAttachments($attachments,$policyId)
    {
        $oldAttachments = db('policy')->where('id',$policyId)->value('attachments');
        $oldAttachments = $oldAttachments ? json_decode($oldAttachments,true):array();
        $add_array = $this->diffValue($attachments,$oldAttachments);
 		
        //根本用不到，因为页面原本就有删除功能的逻辑
//         $delete_array = $this->diffValue($oldAttachments,$attachments);
        
//         if (is_array($delete_array)){
//         	return $oldAttachments;
//             $path_prefix = ROOT_PATH.'Uploads'.DS.'policy'.DS;
//             foreach ($delete_array as $dk => $dv){
//                 $if_unique_used = $this->ifUniqueUsedFile($policyId,$dv['path']);
//                 if ($if_unique_used['if_has'] == true){
//                     continue;
//                 }
//                 $path_name = iconv('utf-8','gb2312',$path_prefix.$dv['path']);
//                 if (file_exists($path_name)){
//                     unlink($path_name);
//                 }
//             }
//         }
        
        if(is_array($add_array)){
            $path_prefix_from = ROOT_PATH.'Uploads'.DS.'policy_temp'.DS;
            $path_prefix_to = ROOT_PATH.'Uploads'.DS.'policy'.DS;
            $remove_array = array();
            foreach ($add_array as $ak => $av){
                $path_name_to = iconv('utf-8','gb2312',$path_prefix_to.$av['path']);
                if (file_exists($path_name_to)){
                    continue;
                }
                $path_name_from = iconv('utf-8','gb2312',$path_prefix_from.$av['path']);
                if (file_exists($path_prefix_from)){
                    rename($path_prefix_from,$path_name_to);
                }else{
                    array_push($remove_array,$av);
                }

            }
            $attachments = $this->diffValue($attachments,$remove_array);
            
        }
        return $attachments;
    }
    
    public function delAttachmentsByPolictId($policyId)
    {
    	$result = array('err' => '1','content' => '');
    	$attachments = db('Policy')->where('id',$policyId)->value('attachments');
    	$attachments = $attachments ? json_decode($attachments,true) : array();
    	try {
    		foreach ($attachments as $ak => $av){
    			$res = $this->del_attachments($policyId, $av['path']);
    			$result['content'] .= $av['name'].':'.$res['message'].';';
    		}
    	}catch (\Exception $e){
    		$result['content'] .= $e->getMessage();
    		return $result;
    	}
    	$result['err'] = '0';
    	$result['content'] = '全部附件处理完成！';
    	return $result;
    		
    }
}